package modelz.latebinding;

import modelz.AbstractUpdateableCollectionListener;
import modelz.Updateable;
import modelz.UpdateableCollection;

public class LateBindingHelper {

	public static <T extends Updateable<T>> void performLateBinding(
			final LateBindingProvider<T> provider,
			final LateBindingListener<T> listener) {
		if (provider == null || listener == null)
			throw new NullPointerException(
					"Late binding provider and listener must be given");

		T item = provider.gatherItem();

		if (item != null) {
			listener.bound(item);
			return;
		}

		// perform late binding
		final UpdateableCollection<T> collection = provider
				.getLateBindingCollection();
		if (collection == null)
			throw new NullPointerException(String.format(
					"Error in LateBindingProvider %s", provider.getClass()
							.getName()));

		collection.addListener(new AbstractUpdateableCollectionListener<T>() {
			public void added(T item) {
				// check if this is really the item we needed
				if (provider.gatherItem() == item) {
					listener.bound(item);
					collection.removeListener(this);
				}
			}
		});
	}

}
